import axios from 'axios'
import Qs from 'qs'
// import { SessionStorage } from 'quasar'
import {
  baseURL,
  POST,
  PUT,
  PATCH,
  DELETE,
  MSGCODE_SUCCESS
} from './consts'
const baseConfig = axios => {
  axios.defaults.baseURL = baseURL
}
const transformRequest = axios => {
  axios.defaults.transformRequest = [
    function (data, headers) {
      // // 添加 Authorization 头信息
      // Object.assign(headers, auth.getAuthHeader())
      // headers['Authorization'] = SessionStorage.getItem('token')
      if (data === undefined) {
        return
      }
      // Qs序列化数组有如下问题，npm 文档描述：
      // When arrays are stringified, by default they are given explicit indices:
      // qs.stringify({ a: ['b', 'c', 'd'] });
      // // 'a[0]=b&a[1]=c&a[2]=d'
      // You may override this by setting the indices option to false:
      // qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });
      // // 'a=b&a=c&a=d'
      if (data.qsJSON) {
        headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
        delete data.qsJSON
        return Qs.stringify(data, { indices: false })
      }
      if (data.emulateFile) {
        headers['Content-Type'] = 'multipart/form-data;charset=UTF-8'
        delete data.emulateFile
        return data.emulateFile
      }
      if (data.emulateJSON) {
        headers['Content-Type'] = 'application/json;charset=UTF-8'
        delete data.emulateJSON
        return JSON.stringify(data)
      }
      if (data.emulateQS) {
        headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
        delete data.emulateQS
        return Qs.stringify(data)
      }
    }
  ]
}
const addRequestInterceptors = axios => {
  axios.interceptors.request.use(
    function (config) {
      if (config.useLoadLayer) {
        // store.commit('loading/CHANGE_LOAD_SHOW_STATE', true)
      }

      if (config.useAjaxBar) {
        // store.commit('loading/CHANGE_AJAXBAR_SHOW_STATE', true)
      }
      // console.log(config.data !== null)
      // for (let i in config.headers) {
      //   var a = config.headers[i]['Content-Type']
      // }
      // if (config.data !== null && config.method === PUT && a === 'application/x-www-form-urlencoded') {
      //   store.commit('axios/MSGCODE_PARAMETER_EX', 'formdata只支持get/post')
      //   return false
      // }
      return config
    },
    function (error) {
      // store.commit('loading/CHANGE_LOAD_SHOW_STATE', false)
      // store.commit('loading/CHANGE_AJAXBAR_SHOW_STATE', false)
      console.error('[request error] ' + error)
      return Promise.reject(error)
    }
  )
  return axios
}
const addResponseInterceptors = axios => {
  axios.interceptors.response.use(
    function (response) {
      // store.commit('loading/CHANGE_LOAD_SHOW_STATE', false)
      // store.commit('loading/CHANGE_AJAXBAR_SHOW_STATE', false)
      return Promise.resolve(response)
    },
    function (error) {
      // store.commit('loading/CHANGE_LOAD_SHOW_STATE', false)
      // store.commit('loading/CHANGE_AJAXBAR_SHOW_STATE', false)
      console.error('[response error] ' + error)
      return Promise.reject(error)
    }
  )
}
const accessInVue = (Vue, axios, name = '$http') => {
  Vue.prototype[name] = axios
}
export const config = (Vue, name) => {
  baseConfig(axios)
  transformRequest(axios)
  addRequestInterceptors(axios)
  addResponseInterceptors(axios)
  accessInVue(Vue, axios, name)
}

export const api = ({
  url,
  method,
  params = {},
  emulateJSON = false,
  emulateQS = false,
  emulateFile = false,
  qsJSON = false,
  useLoadLayer,
  useAjaxBar,
  useNotify,
  timeout = false,
  successCallback,
  errorCallback
}) => {
  let reqConf = { method, url, useLoadLayer, useAjaxBar, useNotify }
  if ((method === POST || method === PUT || method === PATCH || method === DELETE) && emulateJSON) {
    params.emulateJSON = true
  }
  if ((method === POST || method === PUT || method === PATCH || method === DELETE) && qsJSON) {
    params.qsJSON = true
  }
  if ((method === POST || method === PUT || method === PATCH || method === DELETE) && emulateFile) {
    params.emulateFile = true
  }
  if ((method === POST || method === PUT || method === PATCH || method === DELETE) && emulateQS) {
    params.emulateQS = true
  }
  reqConf[(method === POST || method === PUT || method === PATCH || method === DELETE) ? 'data' : 'params'] = params

  if (timeout) {
    axios.defaults.timeout = 100000
  }
  return axios(reqConf)
    .then(response => {
      let code = response.data.code
      if (code + '' === MSGCODE_SUCCESS + '') {
        // 业务级成功
        if (successCallback) {
          return successCallback(response.data) // 这里整个data返回，以便后续有其它额外的处理操作
        }
      } else {
        if (errorCallback) {
          return errorCallback(response.data)
        }
      }
    })
    .catch(error => {
      if (error.response) {
        // 服务端异常（返回的 HTTP 状态码非 2xx）
        errorCallback && errorCallback(error)
      } else {
        // 客户端代码异常（request 预处理、 successCallback 执行报错）或 请求超时
        console.error('[Error]', error.message)
      }
      console.error('[Error.config]', error.config)
    })
}
window.addEventListener('unhandledrejection', function (e) {
  console.log('被抛到全局未捕获的异常', e)
})
